<template>
  <el-popover
    placement="left-start"
    width="400"
    trigger="hover"
    popper-class="popperStuList"
  >
    <div class="studentCommentList" v-if="isRender">
      <div v-if="!newStuList.length">暂无已批阅的学生</div>
      <div
        v-for="(item, index) in newStuList"
        :key="index"
        class="stu"
        @click="handleSelectStu(item.guidelineResults[gitem.guidelineID])"
      >
        <span class="name" :title="item | filterUserName">{{
          item | filterUserName
        }}</span>
        <span class="score">{{
          item.guidelineResults[gitem.guidelineID].guidelineScore
        }}</span>
        <span
          class="comment"
          :title="item.guidelineResults[gitem.guidelineID].guidelineComment"
          >{{ item.guidelineResults[gitem.guidelineID].guidelineComment }}</span
        >
        <div class="name" style="margin-left: auto">
          <span
            class="name"
            v-for="(citem, cindex) in item.children"
            :key="cindex"
            :title="item.children | moreName"
          >
            {{ citem | filterUserName }}
          </span>
        </div>
      </div>
    </div>
    <div
      class="submitTaskReview"
      v-loading="renderingStuData"
      element-loading-background="rgba(255,255,255,.5)"
      slot="reference"
    >
      <div class="submitTaskReviewContent" v-if="!renderingStuData">
        <div class="submitTaskReview-head">
          <div v-if="currReviewStu">
            {{
              currReviewStu.userID !== undefined
                ? currReviewStu.name
                : "未选批阅的学生"
            }}
          </div>
          <div v-else />
          <div>
            <img
              src="../../../../../assets/images/narrowIcon2.png"
              style="display: none"
              alt=""
            />
          </div>
        </div>
        <div class="textareaBox">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="评语："
            v-model="textarea"
            @input="changeComment = true"
          >
          </el-input>
        </div>
        <div class="commentList" v-if="!commentList.length">
          <span
            v-for="(c, cindex) in defaultCommentList"
            :key="cindex"
            :title="c"
            @click="handleSelectComment(c)"
          >
            {{ c }}
          </span>
        </div>
        <div class="commentList" v-else>
          <span
            v-for="(c, cindex) in commentList.slice(0, 5)"
            :key="cindex"
            :title="c"
            @click="handleSelectComment(c)"
          >
            {{ c }}
          </span>
          <div style="display: flex">
            <dropdown
              :text="'更多'"
              :data="commentList.slice(5)"
              v-if="commentList.length > 5"
              @handleSelectComment="handleSelectComment"
            />
            <dropdown :text="'默认'" :data="defaultCommentList" @handleSelectComment="handleSelectComment" />
          </div>
        </div>
        <div class="reviewScore">
          <div>评分：</div>
          <el-input v-model="score" />
        </div>
        <div class="scoreList">
          <span
            v-for="(c, cindex) in defaultScore"
            :key="cindex"
            @click="handleSelectScore(c)"
          >
            {{ c }}
          </span>
        </div>
        <div
          class="submitBtn"
          :class="{
            notDisabled:
              textarea &&
              score >= 0 &&
              currReviewStu &&
              !currReviewStu.notTaskData,
          }"
          @click="handleSubmit"
        >
          完成批阅
        </div>
        <div class="more" v-if="currReviewStu">
          <div>评阅标准</div>
          <img src="../../../../../assets/images/refAnswer.png" alt="" />
          <div class="linear" />
          <div
            class="moreContent"
            v-html="getCurrGuidelineMoreInfo('remarkStandard') || '无'"
          />
        </div>
        <div class="more" v-if="currReviewStu">
          <div>参考答案</div>
          <img src="../../../../../assets/images/refAnswer.png" alt="" />
          <div class="linear" />
          <div
            class="moreContent"
            v-html="getCurrGuidelineMoreInfo('refAnswer') || '无'"
          />
        </div>
      </div>
    </div>
  </el-popover>
</template>

<script>
import { teacherComment } from "@/request/teacher";
import { operType } from "@/util/guidingtextType";
import { mapState } from "vuex";
// import titleVue from "../../../../../components/title/title.vue";
const dropdown = () =>
  import(
    "@/views/teacher/taskReview/components/submitReview/component/dropdown"
  );
import { Session } from"@/util/sessionStorage.js"

export default {
  components: {
    dropdown,
  },
  data() {
    return {
      operType,
      textarea: "",
      score: 0,
      defaultCommentList: [
        "方法还不够熟练哦，加把劲！",
        "不错！",
        "请按要求完成任务",
        "未完成，请补充！",
        "态度决定高度，值得表扬",
      ],
      defaultScore: [50, 60, 70, 80, 90],
      renderingStuData: false,
      changeComment: false,
      newStuList: [],
      isRender: true,
    };
  },
  props: {
    currReviewStu: Object,
    selectTaskInfo: Object,
    gitem: Object,
    currSelectStudentTaskData: Array,
    commentList: Array,
    studentList: Array,
  },
  watch: {
    score(n) {
      if (n > 100) {
        this.score = 100;
      }
    },
    currReviewStu(n) {
      this.renderingStuData = true;
      this.setCommentScore();
      this.$nextTick(() => {
        const timer = setTimeout(() => {
          this.renderingStuData = false;
          clearTimeout(timer);
        }, 250);
      });
    },
    gitem(n) {
      this.renderingStuData = true;
      this.setCommentScore();
      this.$nextTick(() => {
        const timer = setTimeout(() => {
          this.renderingStuData = false;
          clearTimeout(timer);
        }, 250);
      });
      // 切换引导文时更新评语列表
      this.handleChangeReviewStuList()
    },
    newStuList: {
      handler(n) {
        this.isRender = false;
        this.$nextTick(() => {
          this.isRender = true;
        });
      },
      deep: true,
    },
  },
  filters: {
    filterUserName(value) {
      return (
        value.realName ||
        value.nickName ||
        value.email ||
        value.regName ||
        value.stuNum ||
        ""
      );
    },
    moreName(arr) {
      return arr
        .map(
          (item) =>
            item.realName ||
            item.nickName ||
            item.email ||
            item.regName ||
            item.stuNum ||
            ""
        )
        .join("、");
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    getCurrGuidelineMoreInfo() {
      return function (key) {
        const currTask = this.selectTaskInfo.task.data;
        const currGuideline = currTask.guidelines.find(
          (item) => item.guidelineID === this.gitem.guidelineID
        );
        return currGuideline[key];
      };
    },
    getCommentedStuList() {
      const filterStuList = this.currSelectStudentTaskData.filter((item) => {
        const currStuGuideline = item.guidelineResults[this.gitem.guidelineID];
        return (
          currStuGuideline.guidelineScore !== -8 &&
          currStuGuideline.guidelineComment
        );
      });
      return filterStuList;
    },
  },
  created() {
    this.setCommentScore();
    this.handleChangeReviewStuList();
  },
  methods: {
    handleSelectComment(c) {
      this.textarea = c;
    },
    handleSelectScore(c) {
      this.score = c;
    },
    setCommentScore() {
      if (!this.gitem.guidelineID || !this.currReviewStu) return;
      this.textarea = "";
      this.score = 0;
      this.changeComment = false;
      const guideline =
        this.currReviewStu.guidelineResults[this.gitem.guidelineID];
      if (guideline) {
        this.textarea = guideline.guidelineComment;
        this.score =
          this.gitem.operType == "游戏"
            ? guideline.guidelineScore
            : guideline.guidelineScore;
      }
    },
    handleSubmit() {
      if (this.currReviewStu.notTaskData) {
        this.$antdMessage.warning({
          content: "此学生无引导文数据，无法批阅！",
        });
        return;
      }
      if (!this.textarea || this.score < 0) {
        this.$antdMessage.warning({
          content: "请填写评语并输入分数！",
        });
        return;
      }
      if (!this.currReviewStu) {
        this.$antdMessage.warning({
          content: "您还未选择学生，请在引导文中选择学生！",
        });
        return;
      }
      if (!this.gitem) {
        this.$antdMessage.warning({
          content: "请在引导文中选择学生！",
        });
        return;
      }
      if (!this.userInfo.accessToken || !this.userInfo.userID) {
        this.$antdMessage.warning({
          content: "用户信息已过期，请重新登录！",
        });
        return;
      }
      const params = Object.assign({}, this.currReviewStu);
      const currGuideline = params.guidelineResults[this.gitem.guidelineID]
      if (!currGuideline) {
        this.$antdMessage.warning({
          content: "此学生缺少引导文数据，无法批阅！",
        });
        return;
      }
      params.taskGroupID = this.selectTaskInfo.task.data.taskGroupID;
      currGuideline.guidelineScore = this.score;
      currGuideline.guidelineComment = this.textarea;
      currGuideline.commentTime = new Date().getTime();
      currGuideline.commentUserID = this.userInfo.userID;
      delete params.name;
      delete params.stuNum;
      delete params.userID;
      Object.keys(params.guidelineResults).forEach((key) => {
        delete params.guidelineResults[key].chooseNo;
        delete params.guidelineResults[key].uName;
        delete params.guidelineResults[key].userID;
        delete params.guidelineResults[key].iconPath;
        delete params.guidelineResults[key].taskState;
      });
      teacherComment(params).then((res) => {
        if (res.errno === 0) {
          this.$antdMessage.success({
            content: "批阅成功！",
          });
          // 自动切换到下一个学生
          this.$parent.$refs.taskReviewMain?.$refs[
            `guideline-${this.gitem.guidelineID}`
          ][0]?.handleAutoSelectStu();
          this.changeStuData(this.currReviewStu, currGuideline );
          this.changeComment && this.$emit("handleAddComment", this.textarea);
          const data = {guidelineID: this.gitem.guidelineID, guidelineData: currGuideline, currStu: this.currReviewStu}
          this.$emit("changeUserComment", data)
          this.handleChangeTaskState(params)
          this.updateSessionStuData(data)
          this.handleChangeReviewStuList(params.guidelineResults);
          this.$emit("changeTaskState")
        } else {
          this.$antdMessage.warning({
            content: res.message || "批阅失败！",
          });
        }
      });
    },
    handleSelectStu(guideline) {
      this.score = guideline.guidelineScore;
      this.textarea = guideline.guidelineComment;
    },
    changeStuData(user, gObj) {
      let fStu = this.studentList.find((item) => item.userID === user.userID);
      let fTask = fStu?.allTaskResultsInChooseNo?.find(
        (item) => item.taskID === this.selectTaskInfo.task.data.taskID
      );
      if (!fTask) return
      fTask.guidelineResults[this.gitem.guidelineID] = Object.assign({}, gObj);
    },
    handleChangeReviewStuList() {
      if (!this.gitem.guidelineID || !this.currReviewStu) return [];
      let filterStuList = [];
      let guidelineObj = {};
      const taskID = this.selectTaskInfo.task.data.taskID;
      let findFinishTaskStu = this.studentList.filter(
        (item) => item.finishedTaskResultArray.some(sitem => sitem.taskID == taskID)
      );
      findFinishTaskStu.forEach((item) => {
        if (!item?.allTaskResultsInChooseNo?.length) return
        let findTask = item?.allTaskResultsInChooseNo.find(
          (titem) => titem.taskID === taskID
        );
        let findGuideline = findTask?.guidelineResults[this.gitem.guidelineID];
        if (!findGuideline) return;
        const { guidelineScore, guidelineComment } = findGuideline;
        if (guidelineScore !== -8 && guidelineComment) {
          const currStuData = Object.assign({}, item, {
            guidelineResults: findTask.guidelineResults,
          });
          if (guidelineObj[guidelineComment]) {
            let gCommentScore = guidelineObj[guidelineComment][guidelineScore]
            if (gCommentScore) {
              const oldStuInfo = JSON.parse(JSON.stringify(gCommentScore));
              delete oldStuInfo.children;
              guidelineObj[guidelineComment][guidelineScore].children.unshift(oldStuInfo);
              const children = guidelineObj[guidelineComment][guidelineScore].children
              guidelineObj[guidelineComment][guidelineScore] = Object.assign({}, currStuData, {children: children});
            } else {
              guidelineObj[guidelineComment][guidelineScore] = currStuData;
              guidelineObj[guidelineComment][guidelineScore].children = [];
            }
          } else {
            guidelineObj[guidelineComment] = {};
            guidelineObj[guidelineComment][guidelineScore] = currStuData;
            guidelineObj[guidelineComment][guidelineScore].children = [];
          }
        }
      });
      Object.keys(guidelineObj).forEach((item) => {
        Object.keys(guidelineObj[item]).forEach((citem) => {
          filterStuList.push(guidelineObj[item][citem]);
        });
      });
      this.newStuList = filterStuList;
    },
    // 修改session的学习数据
    updateSessionStuData(data) {
      const query = this.$route.query
      const sKey = `${query.currNo}_${query.courseID}`
      const sData = Session.get('stuStudyData')
      const gID = this.selectTaskInfo.task.data.taskGroupID
      const tID = this.selectTaskInfo.task.data.taskID
      const glID = data.guidelineID
      if (sData) {
        const arr = JSON.parse(JSON.stringify(sData[sKey]))
        const findUser = arr.find(item => item.userID == data.currStu.userID)
        if (findUser) {
          const findTask = findUser.allTaskResultsInChooseNo.find(item => item.taskID == tID)
          const findUpdateTaskUser = this.studentList.find(item => item.userID == data.currStu.userID)
          const findTaskState = findUser.finishedTaskResultArray.find(item => item.taskID == tID)
          this.$set(findTaskState, "reviewState", findUpdateTaskUser.finishedTaskResultArray.find(item => item.taskID == tID).reviewState)
          const fGuideline = findTask?.guidelineResults[glID]
          if (fGuideline) {
            Object.assign(fGuideline, data.currStu.guidelineResults[glID])
            this.$set(findTask.guidelineResults,glID, fGuideline)
            sData[sKey] = arr
            Session.set("stuStudyData", sData)
          }
        }
      }
    },
    // 改变任务的状态
    handleChangeTaskState(params) {
      const guidelines = params.guidelineResults
      const oldGuidelines = this.selectTaskInfo.task.data.oldGuidelines
      let isAllReviewed = true
      Object.keys(guidelines).forEach(key => {
        if (oldGuidelines[key]?.operType !== operType['refer']) {
          if (guidelines[key].guidelineScore == -8 || !guidelines[key].guidelineComment) {
            isAllReviewed = false
          }
        }
      })
      this.$emit("handleChangeTaskState", this.currReviewStu, isAllReviewed ? "已批": "在批")
    }
  },
};
</script>

<style lang="stylus">
.popperStuList {
  // padding: 0 10px;
  width: 410px !important;
  // height: 100% !important;
  height: auto;
  max-height: 540px;
  background-color: #ffffff;
  box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.16);
  border: solid 1px rgba(227, 227, 227, 0.2);
  overflow-y: auto;
  overflow-x: hidden;
}

.studentCommentList {
  .stu {
    cursor: pointer;
    padding-top: 12px;
    padding-bottom: 16px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    border-bottom: solid 1px #c4c4c4;

    .name, .score, .comment {
      display: inline-block;
      font-family: Source Han Sans CN;
      font-size: 1rem;
      color: #494949;
    }

    .name {
      min-width: 80px;
      max-width: 80px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .score {
      margin-left: 10px;
      min-width: 22px;
      max-width: 30px;
    }

    .comment {
      margin-left: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .stu:hover {
    background: #fbfcff;
  }
}

.submitTaskReview {
  padding: 13px 5px 10px;
  max-width: 250px;
  min-width: 150px;
  min-height: 560px;
  background-color: #cce4ff;
  // box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.16);
  border-radius: 10px;

  .submitTaskReview-head {
    display: flex;
    justify-content: space-between;
  }

  .textareaBox {
    margin-top: 18px;
    max-width: 100%;

    .el-textarea {
      .el-textarea__inner {
        height: 76px !important;
        resize: none;
      }

      .el-textarea__inner::-webkit-scrollbar {
        cursor: pointer;
        width: 4px;
        height: 1px;
      }

      /* 定义滚动条的滑块的样式有圆角和阴影以及自定义的背景色 */
      .el-textarea__inner::-webkit-scrollbar-thumb {
        -webkit-box-shadow: inset 0 0 1px rgba(195, 197, 198, 0.1);
        background: #ccc;
        border-radius: 10px;
      }

      /* 定义滚动条所在轨道的样式。有圆角和阴影以及淡色系的背景色 */
      .el-textarea__inner::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 1px rgba(195, 197, 198, 0.1);
        border-radius: 4px;
      }
    }
  }

  .commentList {
    span {
      cursor: pointer;
      margin-top: 5px;
      margin-right: 10px;
      display: inline-block;
      padding: 0 4px;
      background: #fff;
      border-radius: 5px;
      border: solid 1px #9fa7b6;
      font-family: Source Han Sans CN;
      font-size: 1rem;
      color: #999999;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      max-width: 100%;
    }
  }

  .reviewScore {
    display: flex;
    align-items: flex-end;
    justify-content: flex-end;
    font-family: PMingLiU-ExtB;
    font-size: 1rem;
    color: #333333;

    .el-input {
      display: inline-block;
      width: 52px;

      .el-input__inner {
        padding: 0 0 0 10px;
        width: 52px;
        background: unset;
        border: none;
        border-bottom: 2px solid #333333;
        border-radius: 0;
        font-family: Roboto;
        font-size: 1rem;
        color: #333934;
      }
    }
  }

  .scoreList {
    margin-top: 10px;
    display: flex;

    span {
      cursor: pointer;
      display: inline-block;
      width: 47px;
      height: 25px;
      text-align: center;
      line-height: 25px;
      background-color: #ffffff;
      border-radius: 5px;
      border: solid 1px #9fa7b6;
    }
  }

  .submitBtn {
    cursor: not-allowed;
    margin-top: 23px;
    width: 100%;
    height: 41px;
    line-height: 41px;
    background-color: #7b7b7b;
    border-radius: 21px;
    text-align: center;
    font-family: Roboto;
    font-size: 1rem;
    color: #ffffff;
  }

  .notDisabled {
    cursor: pointer;
    background: #032d61;
  }

  .more {
    margin-top: 15px;
    display: flex;
    flex-flow: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-family: Source Han Sans CN;
    font-size: 1rem;
    color: rgba(51, 51, 51, 0.4);

    .linear {
      margin-top: 3px;
      width: 100%;
      border-bottom: 1px dashed #707070;
    }

    .moreContent {
      font-family: Source Han Sans CN;
      font-size: 1rem;
      color: rgba(51, 51, 51, 0.4);
    }
  }
}

.commentDropdown {
  .el-dropdown-menu__item {
    max-width: 250px;
    word-break: break-all;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
  }
}
</style>